// ===== DOM加载完成后执行 =====
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initNavigation();
    initScrollAnimations();
    initBackToTop();
    initSmoothScroll();
    initTypingEffect();
    initCounterAnimation();
    initLazyLoading();
    initCommandHighlight();
    initFeatureHover();
    initLanguageSwitcher();
    initBugFeedback();
    initAdminLogin();
});

// ===== 导航栏功能 =====
function initNavigation() {
    const hamburger = document.querySelector('.hamburger');
    const navMenu = document.querySelector('.nav-menu');
    const navLinks = document.querySelectorAll('.nav-link');
    const navbar = document.querySelector('.navbar');

    // 汉堡菜单切换
    if (hamburger) {
        hamburger.addEventListener('click', function() {
            hamburger.classList.toggle('active');
            navMenu.classList.toggle('active');
            document.body.classList.toggle('menu-open');
        });
    }

    // 点击导航链接时关闭移动菜单
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            hamburger?.classList.remove('active');
            navMenu?.classList.remove('active');
            document.body.classList.remove('menu-open');
        });
    });

    // 滚动时导航栏效果
    let lastScroll = 0;
    window.addEventListener('scroll', function() {
        const currentScroll = window.pageYOffset;
        
        // 导航栏背景透明度
        if (currentScroll > 100) {
            navbar.style.background = 'rgba(10, 10, 10, 0.95)';
            navbar.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.3)';
        } else {
            navbar.style.background = 'rgba(10, 10, 10, 0.8)';
            navbar.style.boxShadow = 'none';
        }

        // 导航栏隐藏/显示（向下滚动隐藏，向上滚动显示）
        if (currentScroll > lastScroll && currentScroll > 100) {
            navbar.style.transform = 'translateY(-100%)';
        } else {
            navbar.style.transform = 'translateY(0)';
        }
        
        lastScroll = currentScroll;
    });

    // 高亮当前页面部分的导航链接
    const sections = document.querySelectorAll('section[id]');
    
    window.addEventListener('scroll', function() {
        let current = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            if (pageYOffset >= sectionTop - 200) {
                current = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href').includes(current)) {
                link.classList.add('active');
            }
        });
    });
}

// ===== 滚动动画 =====
function initScrollAnimations() {
    // 创建Intersection Observer来处理滚动动画
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in-up');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    // 观察需要动画的元素
    const animatedElements = document.querySelectorAll(
        '.feature-card, .download-card, .step, .changelog-item, .stat-card'
    );
    
    animatedElements.forEach(el => {
        observer.observe(el);
    });
}

// ===== 返回顶部按钮 =====
function initBackToTop() {
    const backToTopBtn = document.getElementById('back-to-top');
    
    if (backToTopBtn) {
        // 显示/隐藏按钮
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopBtn.classList.add('show');
            } else {
                backToTopBtn.classList.remove('show');
            }
        });

        // 点击返回顶部
        backToTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
}

// ===== 平滑滚动 =====
function initSmoothScroll() {
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetSection = document.getElementById(targetId);
            
            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 80; // 导航栏高度偏移
                
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// ===== 打字效果 =====
function initTypingEffect() {
    const titleElement = document.querySelector('.hero-title .gradient-text');
    
    if (titleElement) {
        const text = titleElement.textContent;
        titleElement.textContent = '';
        titleElement.style.borderRight = '2px solid #4ade80';
        
        let i = 0;
        const typeWriter = function() {
            if (i < text.length) {
                titleElement.textContent += text.charAt(i);
                i++;
                setTimeout(typeWriter, 100);
            } else {
                // 打字完成后移除光标
                setTimeout(() => {
                    titleElement.style.borderRight = 'none';
                }, 1000);
            }
        };
        
        // 延迟开始打字效果
        setTimeout(typeWriter, 500);
    }
}

// ===== 数字计数动画 =====
function initCounterAnimation() {
    const counters = document.querySelectorAll('.stat-number');
    
    const animateCounter = function(counter) {
        const target = parseInt(counter.textContent.replace(/[^0-9]/g, '')) || 0;
        const increment = target / 100;
        let current = 0;
        
        const updateCounter = function() {
            if (current < target) {
                current += increment;
                counter.textContent = Math.ceil(current).toLocaleString();
                requestAnimationFrame(updateCounter);
            } else {
                counter.textContent = target.toLocaleString();
            }
        };
        
        updateCounter();
    };

    // 使用Intersection Observer触发计数动画
    const counterObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const counter = entry.target;
                animateCounter(counter);
                counterObserver.unobserve(counter);
            }
        });
    }, { threshold: 0.5 });

    counters.forEach(counter => {
        // 检查是否是纯数字
        if (/^\d+[\+\,]*$/.test(counter.textContent.trim())) {
            counterObserver.observe(counter);
        }
    });
}

// ===== 懒加载图片 =====
function initLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });

    images.forEach(img => {
        imageObserver.observe(img);
    });
}

// ===== 下载功能 =====
function downloadMod() {
    // 模拟下载
    const downloadBtn = document.querySelector('.btn-download');
    if (downloadBtn) {
        downloadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 下载中...';
        downloadBtn.style.pointerEvents = 'none';
        
        setTimeout(() => {
            downloadBtn.innerHTML = '<i class="fas fa-check"></i> 下载完成';
            downloadBtn.style.background = 'linear-gradient(135deg, #22c55e, #059669)';
            
            setTimeout(() => {
                downloadBtn.innerHTML = '<i class="fas fa-download"></i> 下载模组文件';
                downloadBtn.style.pointerEvents = 'auto';
                downloadBtn.style.background = 'linear-gradient(135deg, #4ade80, #06b6d4)';
            }, 2000);
        }, 1500);
    }
}

// ===== 复制代码功能 =====
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        showNotification('已复制到剪贴板！', 'success');
    }, function() {
        showNotification('复制失败，请手动复制', 'error');
    });
}

// ===== 通知系统 =====
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : 'info'}"></i>
        <span>${message}</span>
    `;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: ${type === 'success' ? '#4ade80' : type === 'error' ? '#ef4444' : '#3b82f6'};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
        transform: translateX(100%);
        transition: transform 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// ===== 视差滚动效果 =====
function initParallaxEffect() {
    window.addEventListener('scroll', function() {
        const scrolled = window.pageYOffset;
        const parallaxElements = document.querySelectorAll('.parallax');
        
        parallaxElements.forEach(element => {
            const speed = element.dataset.speed || 0.5;
            const yPos = -(scrolled * speed);
            element.style.transform = `translateY(${yPos}px)`;
        });
    });
}

// ===== 主题切换（如果需要） =====
function initThemeToggle() {
    const themeToggle = document.querySelector('.theme-toggle');
    const currentTheme = localStorage.getItem('theme') || 'dark';
    
    document.documentElement.setAttribute('data-theme', currentTheme);
    
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            const theme = document.documentElement.getAttribute('data-theme');
            const newTheme = theme === 'dark' ? 'light' : 'dark';
            
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            
            showNotification(`已切换到${newTheme === 'dark' ? '深色' : '浅色'}主题`, 'success');
        });
    }
}

// ===== 搜索功能 =====
function initSearch() {
    const searchInput = document.querySelector('.search-input');
    const searchResults = document.querySelector('.search-results');
    
    if (searchInput) {
        let searchTimeout;
        
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();
            
            if (query.length > 2) {
                searchTimeout = setTimeout(() => {
                    performSearch(query);
                }, 300);
            } else {
                hideSearchResults();
            }
        });
        
        // 点击外部关闭搜索结果
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchResults?.contains(e.target)) {
                hideSearchResults();
            }
        });
    }
}

function performSearch(query) {
    // 模拟搜索结果
    const results = [
        { title: '如何安装模组', url: '#tutorial', type: '教程' },
        { title: '下载最新版本', url: '#download', type: '下载' },
        { title: '功能介绍', url: '#features', type: '功能' },
        { title: '更新日志', url: '#changelog', type: '更新' }
    ].filter(item => 
        item.title.toLowerCase().includes(query.toLowerCase()) ||
        item.type.toLowerCase().includes(query.toLowerCase())
    );
    
    showSearchResults(results);
}

function showSearchResults(results) {
    const searchResults = document.querySelector('.search-results');
    if (!searchResults) return;
    
    if (results.length > 0) {
        searchResults.innerHTML = results.map(result => `
            <a href="${result.url}" class="search-result-item">
                <span class="search-result-title">${result.title}</span>
                <span class="search-result-type">${result.type}</span>
            </a>
        `).join('');
        searchResults.style.display = 'block';
    } else {
        searchResults.innerHTML = '<div class="no-results">未找到相关内容</div>';
        searchResults.style.display = 'block';
    }
}

function hideSearchResults() {
    const searchResults = document.querySelector('.search-results');
    if (searchResults) {
        searchResults.style.display = 'none';
    }
}

// ===== 工具函数 =====
function debounce(func, wait, immediate) {
    let timeout;
    return function executedFunction(...args) {
        const later = function() {
            timeout = null;
            if (!immediate) func(...args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func(...args);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// ===== 性能优化 =====
// 使用防抖和节流优化滚动事件
window.addEventListener('scroll', throttle(function() {
    // 滚动相关的性能敏感操作
}, 16)); // 约60fps

// 预加载重要资源
function preloadResources() {
    const resources = [
        'images/hero-minecraft.png',
        'images/logo.png'
    ];
    
    resources.forEach(resource => {
        const link = document.createElement('link');
        link.rel = 'preload';
        link.as = 'image';
        link.href = resource;
        document.head.appendChild(link);
    });
}

// 页面加载完成后预加载资源
window.addEventListener('load', preloadResources);

// ===== 错误处理 =====
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
    // 这里可以添加错误上报逻辑
});

// ===== 兼容性检查 =====
function checkBrowserCompatibility() {
    const isIE = navigator.userAgent.indexOf('MSIE') !== -1 || 
                 navigator.userAgent.indexOf('Trident') !== -1;
    
    if (isIE) {
        showNotification('检测到您使用的是较旧的浏览器，建议升级以获得最佳体验', 'warning');
    }
}

// 页面加载时检查兼容性
checkBrowserCompatibility();

// ===== 命令高亮功能 =====
function initCommandHighlight() {
    const commandCards = document.querySelectorAll('.command-card');
    
    commandCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 10px 30px rgba(74, 222, 128, 0.2)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.2)';
        });
        
        // 点击复制命令
        const codeElement = card.querySelector('code');
        if (codeElement) {
            card.addEventListener('click', function() {
                const commandText = codeElement.textContent;
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(commandText).then(() => {
                        showNotification('命令已复制: ' + commandText, 'success');
                    });
                } else {
                    // 降级方案
                    const textArea = document.createElement('textarea');
                    textArea.value = commandText;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showNotification('命令已复制: ' + commandText, 'success');
                }
            });
        }
    });
}

// ===== 功能卡片悬停效果 =====
function initFeatureHover() {
    const featureCards = document.querySelectorAll('.feature-card');
    
    featureCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            // 为卡片添加发光效果
            if (!this.classList.contains('featured')) {
                this.style.boxShadow = '0 15px 40px rgba(74, 222, 128, 0.15)';
            }
            
            // 图标动画
            const icon = this.querySelector('.feature-icon i');
            if (icon) {
                icon.style.transform = 'scale(1.2) rotate(5deg)';
                icon.style.color = '#4ade80';
            }
        });
        
        card.addEventListener('mouseleave', function() {
            if (!this.classList.contains('featured')) {
                this.style.boxShadow = '0 5px 20px rgba(0, 0, 0, 0.3)';
            }
            
            const icon = this.querySelector('.feature-icon i');
            if (icon) {
                icon.style.transform = 'scale(1) rotate(0deg)';
                icon.style.color = '';
            }
        });
    });
}

// ===== 页面滚动进度条 =====
function initScrollProgress() {
    // 创建进度条
    const progressBar = document.createElement('div');
    progressBar.id = 'scroll-progress';
    progressBar.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 0%;
        height: 3px;
        background: linear-gradient(90deg, #4ade80, #06b6d4);
        z-index: 9999;
        transition: width 0.1s ease;
    `;
    document.body.appendChild(progressBar);
    
    // 更新进度
    window.addEventListener('scroll', throttle(() => {
        const scrollTop = window.pageYOffset;
        const docHeight = document.documentElement.scrollHeight - window.innerHeight;
        const scrollPercent = (scrollTop / docHeight) * 100;
        progressBar.style.width = scrollPercent + '%';
    }, 16));
}

// 初始化滚动进度条
initScrollProgress();

// ===== Bug反馈页面功能 =====
function initBugFeedback() {
    // 为所有issue header添加点击事件
    const issueHeaders = document.querySelectorAll('.issue-header');
    issueHeaders.forEach(header => {
        header.addEventListener('click', function() {
            toggleIssue(this);
        });
    });
    
    // 初始化在线反馈表单
    initOnlineFeedbackForm();
}

// ===== 在线反馈表单功能 =====
function initOnlineFeedbackForm() {
    const feedbackForm = document.getElementById('feedbackForm');
    
    if (feedbackForm) {
        // 设置placeholder
        updateFormPlaceholders();
        
        // 绑定表单提交事件
        feedbackForm.addEventListener('submit', handleFormSubmit);
        
        // 绑定重置事件
        feedbackForm.addEventListener('reset', handleFormReset);
        
        // 实时验证
        addFormValidation();
    }
}

function updateFormPlaceholders() {
    const placeholderElements = document.querySelectorAll('[data-placeholder-key]');
    placeholderElements.forEach(element => {
        const key = element.getAttribute('data-placeholder-key');
        if (translations[currentLanguage] && translations[currentLanguage][key]) {
            element.placeholder = translations[currentLanguage][key];
        }
    });
}

function handleFormSubmit(e) {
    e.preventDefault();
    
    const form = e.target;
    const formData = new FormData(form);
    
    // 验证表单
    if (!validateForm(form)) {
        return;
    }
    
    // 显示加载状态
    form.classList.add('form-loading');
    
    // 模拟提交过程
    setTimeout(() => {
        // 收集表单数据
        const feedbackData = {
            type: formData.get('type'),
            email: formData.get('email'),
            title: formData.get('title'),
            minecraftVersion: formData.get('minecraftVersion'),
            modVersion: formData.get('modVersion'),
            description: formData.get('description'),
            reproduction: formData.get('reproduction'),
            otherMods: formData.get('otherMods'),
            timestamp: new Date().toISOString(),
            language: currentLanguage
        };
        
        // 保存到本地存储（实际项目中应该发送到服务器）
        saveFeedbackLocally(feedbackData);
        
        // 显示成功消息
        showFeedbackSuccess();
        
        // 移除加载状态
        form.classList.remove('form-loading');
        
        // 清空表单
        form.reset();
        
    }, 2000); // 模拟网络延迟
}

function handleFormReset() {
    // 清除验证状态
    const form = document.getElementById('feedbackForm');
    const errorElements = form.querySelectorAll('.form-error');
    errorElements.forEach(error => error.remove());
    
    // 移除错误样式
    const inputs = form.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.classList.remove('error');
    });
}

function validateForm(form) {
    let isValid = true;
    
    // 清除之前的错误
    const errorElements = form.querySelectorAll('.form-error');
    errorElements.forEach(error => error.remove());
    
    // 验证必填字段
    const requiredFields = [
        { name: 'type', message: '请选择问题类型' },
        { name: 'email', message: '请输入邮箱地址' },
        { name: 'title', message: '请输入问题标题' },
        { name: 'description', message: '请输入详细描述' }
    ];
    
    requiredFields.forEach(field => {
        const input = form.querySelector(`[name="${field.name}"]`);
        const value = input.value.trim();
        
        if (!value) {
            showFieldError(input, field.message);
            isValid = false;
        } else {
            clearFieldError(input);
        }
    });
    
    // 验证邮箱格式
    const emailInput = form.querySelector('[name="email"]');
    const emailValue = emailInput.value.trim();
    if (emailValue && !isValidEmail(emailValue)) {
        showFieldError(emailInput, '请输入有效的邮箱地址');
        isValid = false;
    }
    
    return isValid;
}

function addFormValidation() {
    const form = document.getElementById('feedbackForm');
    const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');
    
    inputs.forEach(input => {
        input.addEventListener('blur', function() {
            validateField(this);
        });
        
        input.addEventListener('input', function() {
            if (this.classList.contains('error')) {
                validateField(this);
            }
        });
    });
}

function validateField(input) {
    const value = input.value.trim();
    const isRequired = input.hasAttribute('required');
    
    if (isRequired && !value) {
        const fieldName = input.closest('.form-group').querySelector('label').textContent;
        showFieldError(input, `${fieldName}不能为空`);
        return false;
    }
    
    if (input.type === 'email' && value && !isValidEmail(value)) {
        showFieldError(input, '请输入有效的邮箱地址');
        return false;
    }
    
    clearFieldError(input);
    return true;
}

function showFieldError(input, message) {
    clearFieldError(input);
    
    input.classList.add('error');
    
    const errorElement = document.createElement('div');
    errorElement.className = 'form-error';
    errorElement.textContent = message;
    errorElement.style.cssText = `
        color: #ef4444;
        font-size: 0.875rem;
        margin-top: 5px;
        display: flex;
        align-items: center;
        gap: 5px;
    `;
    
    const icon = document.createElement('i');
    icon.className = 'fas fa-exclamation-circle';
    errorElement.insertBefore(icon, errorElement.firstChild);
    
    input.parentNode.appendChild(errorElement);
}

function clearFieldError(input) {
    input.classList.remove('error');
    const errorElement = input.parentNode.querySelector('.form-error');
    if (errorElement) {
        errorElement.remove();
    }
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function saveFeedbackLocally(data) {
    // 获取现有反馈
    let feedbacks = JSON.parse(localStorage.getItem('modFeedbacks') || '[]');
    
    // 添加新反馈
    feedbacks.push(data);
    
    // 保存到本地存储
    localStorage.setItem('modFeedbacks', JSON.stringify(feedbacks));
    
    console.log('反馈已保存到本地存储:', data);
}

function showFeedbackSuccess() {
    const form = document.getElementById('feedbackForm');
    const successElement = document.getElementById('feedbackSuccess');
    
    // 隐藏表单，显示成功消息
    form.style.display = 'none';
    successElement.style.display = 'block';
    
    // 滚动到成功消息
    successElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

function resetFeedbackForm() {
    const form = document.getElementById('feedbackForm');
    const successElement = document.getElementById('feedbackSuccess');
    
    // 显示表单，隐藏成功消息
    form.style.display = 'flex';
    successElement.style.display = 'none';
    
    // 清空表单
    form.reset();
    handleFormReset();
    
    // 滚动到表单
    form.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function toggleIssue(header) {
    const issueItem = header.parentElement;
    const isActive = issueItem.classList.contains('active');
    
    // 关闭所有其他的问题项
    document.querySelectorAll('.issue-item.active').forEach(item => {
        if (item !== issueItem) {
            item.classList.remove('active');
        }
    });
    
    // 切换当前项的状态
    if (isActive) {
        issueItem.classList.remove('active');
    } else {
        issueItem.classList.add('active');
    }
}

// ===== 语言切换功能 =====
let currentLanguage = 'zh'; // 默认中文

function initLanguageSwitcher() {
    // 从本地存储获取语言偏好
    const savedLang = localStorage.getItem('preferred-language');
    if (savedLang && translations[savedLang]) {
        currentLanguage = savedLang;
    }
    
    // 初始化语言显示
    updateLanguageDisplay();
    translatePage(currentLanguage);
    
    // 绑定语言切换按钮事件
    const languageToggle = document.getElementById('language-toggle');
    if (languageToggle) {
        languageToggle.addEventListener('click', toggleLanguage);
    }
}

function toggleLanguage() {
    // 切换语言
    currentLanguage = currentLanguage === 'zh' ? 'en' : 'zh';
    
    // 保存语言偏好
    localStorage.setItem('preferred-language', currentLanguage);
    
    // 更新页面内容
    translatePage(currentLanguage);
    updateLanguageDisplay();
    
    // 显示切换提示
    showNotification(
        currentLanguage === 'zh' ? '已切换到中文' : 'Switched to English',
        'success'
    );
}

function updateLanguageDisplay() {
    const langText = document.querySelector('.lang-text');
    if (langText) {
        langText.textContent = currentLanguage === 'zh' ? 'EN' : '中文';
    }
    
    // 更新HTML的lang属性
    document.documentElement.lang = currentLanguage === 'zh' ? 'zh-CN' : 'en';
}

function translatePage(lang) {
    const elements = document.querySelectorAll('[data-key]');
    
    elements.forEach(element => {
        const key = element.getAttribute('data-key');
        if (translations[lang] && translations[lang][key]) {
            // 对于包含HTML的元素，只更新文本内容
            if (element.tagName === 'SPAN' || element.tagName === 'P' || element.tagName === 'H1' || 
                element.tagName === 'H2' || element.tagName === 'H3' || element.tagName === 'A') {
                element.textContent = translations[lang][key];
            } else {
                element.innerHTML = translations[lang][key];
            }
        }
    });
    
    // 更新特殊元素
    updateSpecialElements(lang);
}

function updateSpecialElements(lang) {
    // 更新页面标题
    document.title = lang === 'zh' ? '加强附魔金苹果 - Minecraft 1.21.8 模组' : 
                                    'Enhanced Enchanted Golden Apple - Minecraft 1.21.8 Mod';
    
    // 更新meta描述
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) {
        metaDesc.content = lang === 'zh' ? 
            'Minecraft 1.21.8 加强附魔金苹果模组 - 增强金苹果效果，无限不死图腾，超强火焰弹投掷！' :
            'Minecraft 1.21.8 Enhanced Enchanted Golden Apple Mod - Enhanced golden apples, infinite totems, powerful fireballs!';
    }
    
    // 更新返回顶部按钮
    const backToTop = document.getElementById('back-to-top');
    if (backToTop) {
        backToTop.title = translations[lang]['back_to_top'] || 
                         (lang === 'zh' ? '返回顶部' : 'Back to Top');
    }
    
    // 更新命令复制提示
    updateCommandHints(lang);
    
    // 更新表单placeholder
    updateFormPlaceholders();
}

function updateCommandHints(lang) {
    const commandHints = document.querySelectorAll('.command-hint');
    commandHints.forEach(hint => {
        hint.textContent = translations[lang]['commands.hint'] || 
                          (lang === 'zh' ? '💡 点击卡片复制命令' : '💡 Click card to copy command');
    });
    
    // 更新命令卡片title属性
    const commandCards = document.querySelectorAll('.command-card[title]');
    commandCards.forEach(card => {
        card.title = lang === 'zh' ? '点击复制命令' : 'Click to copy command';
    });
}

// 重写命令复制功能以支持多语言提示
function initCommandHighlight() {
    const commandCards = document.querySelectorAll('.command-card');
    
    commandCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 10px 30px rgba(74, 222, 128, 0.2)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.2)';
        });
        
        // 点击复制命令
        const codeElement = card.querySelector('code');
        if (codeElement) {
            card.addEventListener('click', function() {
                const commandText = codeElement.textContent;
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(commandText).then(() => {
                        const message = translations[currentLanguage]['commands.copied'] + ': ' + commandText ||
                                       (currentLanguage === 'zh' ? '命令已复制: ' : 'Command copied: ') + commandText;
                        showNotification(message, 'success');
                    });
                } else {
                    // 降级方案
                    const textArea = document.createElement('textarea');
                    textArea.value = commandText;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    const message = translations[currentLanguage]['commands.copied'] + ': ' + commandText ||
                                   (currentLanguage === 'zh' ? '命令已复制: ' : 'Command copied: ') + commandText;
                    showNotification(message, 'success');
                }
            });
        }
    });
}

// ===== 管理员登录功能 =====
function initAdminLogin() {
    const adminBtn = document.getElementById('admin-login');
    
    if (adminBtn) {
        adminBtn.addEventListener('click', function() {
            showAdminLoginModal();
        });
    }
}

function showAdminLoginModal() {
    // 创建登录模态框
    const modal = document.createElement('div');
    modal.className = 'admin-modal';
    modal.innerHTML = `
        <div class="admin-modal-content">
            <div class="admin-modal-header">
                <h3><i class="fas fa-shield-alt"></i> 管理员登录</h3>
                <button class="admin-modal-close">&times;</button>
            </div>
            <div class="admin-modal-body">
                <form id="admin-login-form">
                    <div class="admin-form-group">
                        <label for="admin-username">用户名:</label>
                        <input type="text" id="admin-username" name="username" required>
                    </div>
                    <div class="admin-form-group">
                        <label for="admin-password">密码:</label>
                        <input type="password" id="admin-password" name="password" required>
                    </div>
                    <div class="admin-form-actions">
                        <button type="submit" class="admin-login-btn">
                            <i class="fas fa-sign-in-alt"></i> 登录
                        </button>
                        <button type="button" class="admin-cancel-btn" onclick="closeAdminModal()">
                            取消
                        </button>
                    </div>
                </form>
                <div class="admin-demo-info">
                    <p><i class="fas fa-info-circle"></i> 演示账号: admin / admin123</p>
                </div>
            </div>
        </div>
    `;
    
    // 添加模态框样式
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
        backdrop-filter: blur(10px);
    `;
    
    const modalContent = modal.querySelector('.admin-modal-content');
    modalContent.style.cssText = `
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        border-radius: 20px;
        padding: 0;
        max-width: 400px;
        width: 90%;
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        overflow: hidden;
    `;
    
    const modalHeader = modal.querySelector('.admin-modal-header');
    modalHeader.style.cssText = `
        background: linear-gradient(135deg, #4ade80, #06b6d4);
        color: white;
        padding: 20px 25px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    `;
    
    const modalBody = modal.querySelector('.admin-modal-body');
    modalBody.style.cssText = `
        padding: 30px 25px;
    `;
    
    const formGroups = modal.querySelectorAll('.admin-form-group');
    formGroups.forEach(group => {
        group.style.cssText = `
            margin-bottom: 20px;
        `;
        
        const label = group.querySelector('label');
        if (label) {
            label.style.cssText = `
                display: block;
                color: rgba(255, 255, 255, 0.8);
                margin-bottom: 8px;
                font-weight: 500;
            `;
        }
        
        const input = group.querySelector('input');
        if (input) {
            input.style.cssText = `
                width: 100%;
                padding: 12px 15px;
                background: rgba(255, 255, 255, 0.05);
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                color: white;
                font-size: 14px;
                transition: all 0.3s ease;
            `;
        }
    });
    
    const formActions = modal.querySelector('.admin-form-actions');
    formActions.style.cssText = `
        display: flex;
        gap: 15px;
        margin-top: 25px;
    `;
    
    const loginBtn = modal.querySelector('.admin-login-btn');
    loginBtn.style.cssText = `
        flex: 1;
        padding: 12px 20px;
        background: linear-gradient(135deg, #4ade80, #06b6d4);
        border: none;
        border-radius: 10px;
        color: white;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    `;
    
    const cancelBtn = modal.querySelector('.admin-cancel-btn');
    cancelBtn.style.cssText = `
        flex: 1;
        padding: 12px 20px;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 10px;
        color: white;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    `;
    
    const demoInfo = modal.querySelector('.admin-demo-info');
    demoInfo.style.cssText = `
        margin-top: 20px;
        padding: 15px;
        background: rgba(74, 222, 128, 0.1);
        border-radius: 10px;
        border: 1px solid rgba(74, 222, 128, 0.2);
    `;
    
    const demoInfoP = demoInfo.querySelector('p');
    demoInfoP.style.cssText = `
        color: #4ade80;
        font-size: 13px;
        margin: 0;
    `;
    
    const closeBtn = modal.querySelector('.admin-modal-close');
    closeBtn.style.cssText = `
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
        padding: 5px;
        opacity: 0.8;
        transition: opacity 0.3s ease;
    `;
    
    document.body.appendChild(modal);
    
    // 绑定事件
    const form = modal.querySelector('#admin-login-form');
    form.addEventListener('submit', handleAdminLogin);
    
    closeBtn.addEventListener('click', closeAdminModal);
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeAdminModal();
        }
    });
    
    // 聚焦用户名输入框
    setTimeout(() => {
        modal.querySelector('#admin-username').focus();
    }, 100);
}

function handleAdminLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('admin-username').value;
    const password = document.getElementById('admin-password').value;
    
    // 简单的演示验证
    if (username === 'admin' && password === 'admin123') {
        showNotification('登录成功，正在跳转...', 'success');
        closeAdminModal();
        
        setTimeout(() => {
            window.location.href = 'admin-dashboard.html';
        }, 1000);
    } else {
        showNotification('用户名或密码错误', 'error');
        
        // 添加错误效果
        const form = document.getElementById('admin-login-form');
        form.style.animation = 'shake 0.5s ease';
        setTimeout(() => {
            form.style.animation = '';
        }, 500);
    }
}

function closeAdminModal() {
    const modal = document.querySelector('.admin-modal');
    if (modal) {
        modal.style.opacity = '0';
        modal.style.transform = 'scale(0.9)';
        setTimeout(() => {
            document.body.removeChild(modal);
        }, 300);
    }
}

// 添加shake动画样式
const shakeStyle = document.createElement('style');
shakeStyle.textContent = `
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-5px); }
        75% { transform: translateX(5px); }
    }
`;
document.head.appendChild(shakeStyle);